package net.adetech.crj.service;

import com.alibaba.fastjson.JSONObject;
import net.adetech.crj.utils.ServiceUtil;
import net.adetech.framework.entity.ServiceRequest;
import net.adetech.framework.entity.ServiceResponse;
import net.adetech.framework.utils.SerializeUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("cjg.service")
public class OuterCJGServiceService implements BaseService {



    @Override
    public Map<String, Object> invoke(Map<String, Object> params) {
        String url = (String)params.get("url");
        String serviceName = (String)params.get("serviceName");

        ServiceRequest serviceRequest = new ServiceRequest();
        serviceRequest.setServiceName(serviceName);
        serviceRequest.setParams(params);

        String requestString = SerializeUtil.objectToString(serviceRequest);
        try {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("data",requestString));
            HttpEntity reqEntity = new UrlEncodedFormEntity(paramList,"utf-8");
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setEntity(reqEntity);
            HttpResponse httpResponse = client.execute(post);
            String responseString = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            String resultString = jsonObject.getString("result");
            ServiceResponse serviceResponse = (ServiceResponse) SerializeUtil.stringToObject(resultString);
            return serviceResponse.getResults();

        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
